import React, { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom'
import { Menu } from 'antd';
import { DesktopOutlined, PieChartOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import MenuItem from 'antd/es/menu/MenuItem';

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
): MenuItem {
    return {
        key,
        icon,
        children,
        label,
    } as MenuItem;
}
  
const items: MenuItem[] = [
    getItem('Page1', '/page1', <PieChartOutlined />),
    getItem('Page2', '/page2', <DesktopOutlined />),
    getItem('Items', '/item', <DesktopOutlined />,[
        getItem('Page3', '/item/page3'),
        getItem('Page4', '/item/page4'),
    ]),
    getItem('Other', '/other', <DesktopOutlined />,[
        getItem('404', '/other/404'),
    ]),
];
function MainMenu() {
    const navigateTo = useNavigate()
    const currentRoute = useLocation()
    const initOpenKeys = '/' + currentRoute.pathname.split('/')[1]
    const [openKeys, setOpenKeys] = useState([initOpenKeys]);
    const menuClick = (e: {key: string}) => {
        navigateTo(e.key)
    }
    const handleOpenChange = (keys: string[]) => {
        setOpenKeys([keys[keys.length - 1]])
    }
    return(
        <Menu 
            theme="light" 
            selectedKeys={[currentRoute.pathname]} 
            mode="inline"
            items={items} 
            onClick={menuClick}
            onOpenChange={handleOpenChange}
            openKeys={openKeys}
        />
    )
}

export default MainMenu